<template>
  <div class="woodland">
    <div class="woodland_top">
      <div class="woodland_top_text">
        林地
      </div>
      <el-switch
        v-model="switchValue"
        active-color="#409EFF"
        inactive-color="#d1d1d1"
        @change="switchChange"
        :disabled="isdisabled"
      >
      </el-switch>
    </div>
    <div class="woodland_middle">
      <div class="woodland_middle_title">
        影响林地情况统计
      </div>
      <div
        v-if="ResultData.length && ResultData[0].ha != 0"
        class="woodland_middle_content"
      >
        <div
          id="qstView"
          class="qstViewClass"
          style="width: 460px; height: 280px"
        ></div>
      </div>
      <div v-else class="woodland_middle_content_else">
        <div class="woodland_middle_content_else_top">
          选址不涉及商品林与公益林
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { mapActions, mapState } from "vuex";
import { getXzRegion } from "../../../../../api/connect.js";
import tableNames from "../../left/tableNames.json";
import { editMap } from "../../../../../utils/map.js";

export default {
  data() {
    return {
      option: {
        // tooltip: {
        //   trigger: 'axis',
        //   // axisPointer: {
        //   //   type: 'shadow'
        //   // }
        // },
        legend: {
          show: false,
        },
        grid: {
          top: "6%",
          left: "0%",
          right: "10%",
          bottom: "6%",
          containLabel: true,
        },
        // dataZoom: [
        //   {
        //     show: true,
        //     right: 0,
        //     start: 0, //数据窗口范围的起始百分比,表示30%
        //     end: 100, //数据窗口范围的结束百分比,表示70%
        //     startValue: 0, //数据窗口范围的起始数值
        //     endValue: 100,
        //     orient: "vertical",
        //     // type:'inside',
        //     width: 8,
        //     brushSelect: false,
        //     zoomLock: true, //锁定滚动区域
        //     // backgroundColor: "rgba(86, 166, 253, 0.1)", //滚动条底部的颜色
        //     borderColor: "rgba(86, 166, 253, 0.3)", // 边框颜色
        //     showDataShadow: false, //去除原始组件上的数据阴影
        //     showDetail: false,
        //     fillerColor: "rgba(86, 166, 253, 0.3)",
        //     dataBackground: {
        //       areaStyle: {
        //         color: "rgba(86, 166, 253, 0.3)",
        //       },
        //     },
        //   },
        //   {
        //     //没有下面这块的话，只能拖动滚动条，鼠标滚轮在区域内不能控制外部滚动条
        //     type: "inside",
        //     yAxisIndex: 0,
        //     zoomOnMouseWheel: false, //滚轮是否触发缩放
        //     moveOnMouseMove: true, //鼠标滚轮触发滚动
        //     moveOnMouseWheel: true,
        //   },
        // ],
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.2],
          axisLabel: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,0.1)",
              type: "dashed",
            },
          },
        },
        yAxis: {
          type: "category",
          data: [
            "农村道路",
            "竹林地",
            "其他草地",
            "灌木林地",
            "公路用地",
            "沟渠",
            "农村宅基地",
            "坑塘水面",
            "工业用地",
            "水田",
            "果园",
            "乔木森林",
          ],
          axisTick: {
            show: false,
          },
          axisLine: {
            show: true, //添加x轴最底下的线
            lineStyle: {
              color: "rgba(157,175,191,0.6)",
            },
          },
          axisLabel: {
            fontSize: 14,
            color: "#ffffff",
          },
        },
        series: [
          {
            type: "bar",
            data: [
              2312,
              3123,
              1312,
              5534,
              34534,
              34534,
              19325,
              23438,
              31000,
              121594,
              134141,
              24075.19,
            ],
            itemStyle: {
              color: "rgba(87, 167, 255, 0.3)",
              borderWidth: 1,
              borderColor: "#57A7FF",
            },
            barWidth: 15,
            label: {
              show: true,
              position: "right",
              formatter: "{c}平方米",
              // color: "#57A7FF",
              color: "#ffffff",
              fontSize: 12,
              // fontFamily: "HuXiaoBo-NanShen",
              fontWeight: 400,
            },
          },
        ],
      },
      // y轴数据
      yData: [],

      //switch的值
      switchValue: false,
      isdisabled: false, //是否禁用
      // 林地图层的loading
      ldLoading: false,

      // 保存林地的itemJsons
      itemJsons: null,

      // 保存林地里的画面数据
      polygondata: [],
      polylinedata: [],
    };
  },
  computed: {
    ...mapState("Sjsx", [
      "ResultData",
      "unit",
      "isRegion",
      "tuliData",
      "polygonType",
      "polygonTypeId",
    ]),
  },
  mounted() {
    this.getEcharts();
    console.log("%c ResultData", "color:red", this.ResultData);
    this.changeData();
  },
  watch: {
    polygonTypeId(newVal, oldVal) {
      console.log(newVal, "新的newVal");
    },
  },
  methods: {
    ...mapActions({
      setLdLoading_act: "Sjsx/setLdLoading_act",
      setTuliData_act: "Sjsx/setTuliData_act",
      setTuliPolygonData_act: "Sjsx/setTuliPolygonData_act",
      setTuliPolyLineData_act: "Sjsx/setTuliPolyLineData_act",
      setPolygonType_act: "Sjsx/setPolygonType_act",
    }),
    getEcharts() {
      if (this.ResultData.length !== 0) {
        var mychart = echarts.init(document.getElementById("qstView"));
        mychart.setOption(this.option);
      }
    },
    changeData() {
      if (this.ResultData.length !== 0) {
        this.option.yAxis.data = [];
        this.option.series[0].data = [];
        this.ResultData.forEach((item) => {
          this.option.yAxis.data.push(item.subCategory);

          this.option.series[0].data.push(item.ha);
          this.option.series[0].label.formatter = "{c} 公顷";
        });
        console.log(this.option.yAxis.data, "ydata");
        console.log(this.option.series[0].data, "seriersdata");
        this.getEcharts();
      }
    },

    // 点击后画面
    async getRegionData() {
      try {
        const temp = JSON.parse(
          JSON.stringify(
            tableNames.find((r) => r.layer_chinese_name === "林地")
          )
        );
        console.log(temp, "temp的值");
        if (this.switchValue == true) {
          const result = await getXzRegion(this.isRegion, temp);
          const polygondata = [];
          const polylinedata = [];
          let Type = [];

          result.data.map((item, index) => {
            let itemJson = JSON.parse(item);
            Type.push(itemJson.properties.type);
            console.log(Type, "Type的值");
            console.log(itemJson, "itemJson");

            const field_value = itemJson.properties.field_value;
            const type = itemJson.properties.type;
            let color = "#FFFF00";
            if (temp.hex instanceof Array) {
              let colorTemp = temp.hex.find(
                (p) => p.field_value === field_value && p.type === type
              );
              if (!colorTemp) {
                colorTemp = temp.hex.find((p) => p.field_value === "default");
              }
              color = colorTemp.hex;
            } else {
              color = temp.hex;
            }
            const r = parseInt(color.substr(1, 2), 16) / 255;
            const g = parseInt(color.substr(3, 2), 16) / 255;
            const b = parseInt(color.substr(5, 2), 16) / 255;
            const colorArray = [r, g, b, 0.5];
            let o = {
              id: "polygon_" + temp.layer_english_name + "_" + index,
              GroupID:"switch_Polygon",
              coordinates: itemJson.geometry.coordinates,
              // color: [
              //   0.2784313725490196,
              //   0.8117647058823529,
              //   0.0745098039215686,
              //   0.7,
              // ], //多边形的填充颜色
              userData: JSON.stringify(itemJson.properties),
              color: colorArray,
              frameColor: [1, 1, 0, 0.8], //边框颜色
              frameThickness: 2, //边框厚度
              intensity: 1, //亮度
              // style: window.PolygonStyle.SingleColor, //单色 请参照API开发文档选取枚举
              style: 0,
              depthTest: false, //是否做深度检测
              //   coordinateType: 1,
            };
            // if (this.XzTreeDataPolyon.indexOf(o.id) < 0) {
            //   this.XzTreeDataPolyon.push(o.id);
            // }
            polygondata.push(o);

            itemJson.geometry.coordinates &&
              itemJson.geometry.coordinates.forEach((item) => {
                // console.log(item, "item");
                if (
                  item instanceof Array &&
                  item[0] instanceof Array &&
                  item[0][0] instanceof Array
                ) {
                  item.forEach((mon) => {
                    polylinedata.push({
                      id: "polyline_" + temp.layer_english_name + "_" + index,
                      GroupID:"switch_Polygon",
                      coordinates: mon, //构成折线的坐标点数组
                      color: [1, 1, 1, 1], //折线颜色
                      style: 0, //折线样式 参考样式枚举：PolylineStyle
                      thickness: 5, //折线宽度
                      userData: JSON.stringify(itemJson.properties),
                      intensity: 1, //亮度
                      flowRate: 0.5, //流速
                      tiling: 0, //材质贴图平铺比例
                      shape: 0, //折线类型 0：直线， 1：曲线
                      depthTest: false, //是否做深度检测
                      coordinateType: 0,
                    });
                  });
                } else {
                  polylinedata.push({
                    id: "polyline_" + temp.layer_english_name + "_" + index,
                    GroupID:"switch_Polygon",
                    coordinates: item, //构成折线的坐标点数组
                    color: [1, 1, 1, 1], //折线颜色
                    style: 0, //折线样式 参考样式枚举：PolylineStyle
                    thickness: 5, //折线宽度
                    userData: JSON.stringify(itemJson.properties),
                    intensity: 1, //亮度
                    flowRate: 0.5, //流速
                    tiling: 0, //材质贴图平铺比例
                    shape: 0, //折线类型 0：直线， 1：曲线
                    depthTest: false, //是否做深度检测
                    coordinateType: 0,
                  });
                }
              });
          });

          //   temp["polygondata"] = polygondata;
          //   temp["polylinedata"] = polylinedata;
          this.polygondata = polygondata;
          this.polylinedata = polylinedata;
          // debugger;

          // 高亮代码
          let polygonType = [];
          console.log(polygondata, "polygondata的值");
          polygondata.forEach((item) => {
            polygonType.push(item);
          });
          console.log(polygonType, "----polygon的Type----");

          polygonType.forEach(item => {
            item['typeName'] = '林地'
          })
          
          // !this.polygonType || this.polygonType.length === 0
          //   ? this.setPolygonType_act([polygonType])
          //   : this.setPolygonType_act([...this.polygonType, polygonType]);
          // console.log(this.polygonType,"---12345---");
          this.setPolygonType_act(polygonType);

          console.log(polygondata, "polygondata值");
          this.setTuliPolygonData_act({ text: "林地", ids: polygondata }); // 将画面的数据传到图例中
          this.setTuliPolyLineData_act({ text: "林地", ids: polylinedata }); // 将画线的数据传到图例中

          // 调用一次性画3000条数据的方法
          await editMap(polylinedata, 1);
          await editMap(polygondata, 2);

          this.ldLoading = false;
          this.setLdLoading_act(this.ldLoading);

          console.log(this.tuliData, "tuliData");
          console.log(temp, "temp,之前");

          // 过滤
          let filterHex = temp.hex.filter((item) => Type.includes(item.type));
          console.log(filterHex, "filterHex");
          temp.hex = filterHex;
          temp.hex.unshift({
            field_value: "default",
            hex: "#808080",
            layer_class_field: "SEN_LIN_LB",
            type: "其他",
          });

          console.log(temp, "temp,之后");
          // 判断vuex中是否有存储图例，无则直接加入，有则追加加入
          !this.tuliData || this.tuliData.length === 0
            ? this.setTuliData_act([temp])
            : this.setTuliData_act([...this.tuliData, temp]);

          // await window.__g.polyline.add(polylinedata);
          // await window.__g.polygon.add(polygondata);

          // await window.__g.polygon.focus(polygondata.map((r) => r.id));
        } else if (this.switchValue == false) {
          if (this.polygondata && this.polygondata instanceof Array) {
            // debugger;
            // window.__g.polygon.updateBegin();
            let polygondataIds = [];
            let polylineIds = [];

            this.polygondata.forEach((element) => {
              polygondataIds.push(element.id);
            });
            this.polylinedata.forEach((element) => {
              polylineIds.push(element.id);
            });
            // console.log(this.polygonTypeId,"林地里的polygonTypeId");
            await window.__g.polygon.delete(this.polygonTypeId); // 关闭高亮的图层
            await window.__g.polygon.delete(polygondataIds);
            await window.__g.polyline.delete(polylineIds);

            // window.__g.polygon.updateEnd();
            console.log("已经删除");
          }
        }
      } catch (error) {
        console.log(error);
        this.$message.error("服务器请求异常，图层加载失败！");
        this.switchValue = false; //请求失败后，将switch框设置为false
        this.ldLoading = false;
        this.setLdLoading_act(this.ldLoading); // 请求失败后，关闭loading窗
      }
    },

    // switch的改变
    async switchChange(val) {
      console.log(val, "switch改变");

      this.isdisabled = true;
      // this.$store.dispatch("Sjsx/setTuliData_act", null);

      if (val) {
        if (this.ResultData.length && this.ResultData[0].ha != 0) {
          this.ldLoading = true;
          this.setLdLoading_act(this.ldLoading);
          // this.$store.dispatch("Sjsx/setLdLoading_act", this.ldLoading);

          // this.switchValue = val;
          const temp = tableNames.find((r) => r.layer_chinese_name === "林地");

          console.log(temp.hex, "temp.hex的值");
          await this.getRegionData();
          // this.ldLoading = false;
          // this.$store.dispatch("Sjsx/setLdLoading_act", this.ldLoading);
          // this.$store.dispatch("Sjsx/setTuliData_act", temp.hex);
        } else {
          this.$message.warning("选址不涉及，暂无图层");
          setTimeout(() => {
            this.switchValue = false;
          }, 300);
        }
      } else {
        await this.getRegionData();
        // 当关闭图层时，将该数组的最后一项取出
        // let a = []
        // a = this.tuliData.pop();
        let test = this.tuliData.filter(
          (item) => item.layer_chinese_name != "林地"
        );
        console.log(test, "test");
        console.log(this.tuliData,"关闭时的tulidata");
        this.setTuliData_act(test);
        // this.$store.dispatch("Sjsx/setTuliData_act", null);


        // let test2 = this.polygonType.filter(item => {
        //   item.forEach(mon => {
        //     mon.typeName != '林地'
        //   })
        // })
        // console.log(test2,"test2");
        // console.log(this.polygonType,"关闭时的polygondata");
        // this.setPolygonType_act(test2);
      }
      this.isdisabled = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.woodland {
  margin-top: 20px;
  .woodland_top {
    background: url("../../../../../assets/images/home/top.png");
    width: 440px;
    background-size: cover;
    display: flex;
    align-items: center;
    .woodland_top_text {
      padding-left: 16px;
      font-family: OPPOSans;
      font-style: normal;
      font-weight: normal;
      font-size: 20px;
      line-height: 24px;
      color: #ffffff;
      margin-right: 120px;
    }
  }
  .woodland_middle {
    display: flex;
    flex-direction: column;
    padding-left: 15px;
    margin-top: 10px;
    .woodland_middle_title {
      font-size: 18px;
    }
    .woodland_middle_content {
      .qstViewClass {
        width: 420px;
        height: 260px;
        border-radius: 8px;
      }
    }
    .woodland_middle_content_else {
      margin: 15px 0 0 0;
      width: 430px;
      height: 100px;
      background: linear-gradient(180deg, #1f3e72 0%, #112650 100%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
      cursor: pointer;
      .woodland_middle_content_else_top {
        font-family: OPPOSans;
        font-style: normal;
        font-weight: normal;
        font-size: 18px;
        line-height: 21px;
        color: rgba(255, 255, 255, 0.85);
        // padding-left: 20px;
      }
    }
  }
}
</style>
